import React from 'react'
import {connect} from 'react-redux'
import {List,Badge} from 'antd-mobile'
import {getLast} from '../../util'
@connect(
    state=>state
)
class Msg extends React.Component{
    render(){
        
        const msgGroup={}
        this.props.chat.chatmsg.forEach(v => {
            if(v.from==this.props.user._id||v.to==this.props.user._id){
                msgGroup[v.chatid]=msgGroup[v.chatid]||[];
                msgGroup[v.chatid].push(v)
            }
            
        });
        const chatList=Object.values(msgGroup).sort((a,b)=>{
            const a_last=getLast(a).create_time;
            const b_last=getLast(b).create_time;
            return b_last-a_last
        })

        console.log('====================================');
        console.log(chatList);
        console.log('====================================');
        const userid=this.props.user._id;
        const Item=List.Item;
        const Brief=Item.Brief
        return(
            <div>
                    {chatList.map(v=>{
                        const lastItem=getLast(v);
                        const unreadNum=v.filter(v=>!v.read&&v.to==userid).length
                        const targetId=lastItem.to==userid?lastItem.from:lastItem.to
                        return(
                            <List  key={lastItem._id}>
                                <Item
                                    onClick={()=>{this.props.history.push(`/chat/${targetId}`)}}
                                    arrow='horizontal'
                                    extra={<Badge text={unreadNum}></Badge>}
                                    thumb={require(`../img/${lastItem.avatar}.png`)}
                                >
                                    {lastItem.content} 
                                    <Brief>{lastItem.msg_from} </Brief>
                                </Item>
                                
                            </List>
                        )
                    })}
            </div>
        )
    }
    componentDidMount() {
        
    }
}
export default Msg